﻿using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace Rampant.Muninn
{
    public abstract class RssElement
    {
        private XElement _rssSourceElement;
        public string Name { get; set; }
        public string Value { get; set; }
        public Dictionary<string, string> Attributes{get; set;}
        public RssElement(XElement rssSourceElement)
        {
            _rssSourceElement = rssSourceElement;
            Name = rssSourceElement.Name.ToString();
            Value = rssSourceElement.Value;
            
            var attributes = from a in _rssSourceElement.Attributes()
                             select a;
            Attributes = new Dictionary<string, string>();
            foreach (XAttribute attribute in attributes)
            {
                Attributes.Add(attribute.Name.ToString(), attribute.Value);
            }
        }
        public List<RssElement> GetElements(string parentXName, string XName)
        {
            List<RssElement> list = new List<RssElement>();
            IEnumerable<XElement> values = from elem in _rssSourceElement.DescendantsAndSelf(parentXName)
                                           select elem.Element(XName);
            foreach( XElement e in values)
            {
                if( e != null)
                    list.Add((RssElement)e);
            }
            return list;
        }
        public RssElement GetElement(string parentXName, string XName)
        {
            var values = GetElements(parentXName, XName);
            if( values.Count == 0)
            {
                values.Add(new RssNode(new XElement(XName)));
            }
            return values.First<RssElement>();
        }
        public static implicit operator RssElement(XElement xElem)
        {
            return (RssElement)new RssNode(xElem);
        }
        private class RssNode : RssElement
        {   //TODO: Cheat... Gotta leave myself /something/ to fix later ;) 
            public RssNode(XElement nodeSource) : base(nodeSource){}
        }
    }
}
